Skip to content

Conversation

jborean93
Copy link
Contributor

PR Summary

Adds the pathMappings option to the debugger that can be used to map a local to remote path and vice versa. This is useful if the local environment has a checkout of the files being run on a remote target but at a different path. The mappings are used to translate the paths that will the breakpoint will be set to in the target PowerShell instance. It is also used to update the stack trace paths received from the remote.

For a launch scenario, the path mappings are also used when launching a script if the integrated terminal has entered a remote runspace.

PR Context

Fixes: #2242

@Copilot Copilot AI review requested due to automatic review settings July 31, 2025 06:00
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds a pathMappings option to the PowerShell debugger that enables mapping between local and remote file paths during debugging sessions. This is particularly useful when debugging remote PowerShell instances where the local development environment has the same files but at different paths.

Key changes:

  • Adds PathMapping record to define local-to-remote path mappings
  • Integrates path mapping logic into breakpoint setting, stack trace handling, and script launching
  • Adds comprehensive end-to-end test for attach scenarios with path mappings

Reviewed Changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
PathMapping.cs New record defining the structure for local/remote path mappings
DebugService.cs Core path mapping logic with methods to translate between local and remote paths
LaunchAndAttachHandler.cs Integration of path mappings into launch and attach request handling
StackTraceHandler.cs Updates stack trace paths using path mappings for remote debugging
BreakpointService.cs Modified to use mapped paths when setting breakpoints
BreakpointApiUtils.cs Added script path override parameter for breakpoint setting
DisconnectHandler.cs Cleanup of path mappings on disconnect
DscBreakpointCapability.cs Minor refactor to extract module name instead of full module info
DebugAdapterProtocolMessageTests.cs Comprehensive E2E test for path mapping functionality
Comments suppressed due to low confidence (1)

test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs:580

  • Spelling error: 'cotinue' should be 'continue'.
                // background and requesting the st is the only wait to ensure

Comment on lines 626 to 624
if (remotePath.StartsWith(mapping.RemoteRoot, StringComparison.OrdinalIgnoreCase))
{
localPath = mapping.LocalRoot + remotePath.Substring(mapping.RemoteRoot.Length);
Copy link
Preview

Copilot AI Jul 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Path comparison using StartsWith without ensuring proper path separators could lead to incorrect matches. For example, '/home/user' would incorrectly match '/home/username/file.ps1'. Consider using proper path comparison logic that respects directory boundaries.

Suggested change
if (remotePath.StartsWith(mapping.RemoteRoot, StringComparison.OrdinalIgnoreCase))
{
localPath = mapping.LocalRoot + remotePath.Substring(mapping.RemoteRoot.Length);
string normalizedRemotePath = Path.GetFullPath(remotePath);
string normalizedRemoteRoot = Path.GetFullPath(mapping.RemoteRoot);
if (normalizedRemotePath.StartsWith(normalizedRemoteRoot, StringComparison.OrdinalIgnoreCase) &&
Path.GetRelativePath(normalizedRemoteRoot, normalizedRemotePath).IndexOf("..", StringComparison.Ordinal) != 0)
{
localPath = Path.Combine(mapping.LocalRoot, Path.GetRelativePath(normalizedRemoteRoot, normalizedRemotePath));

Copilot uses AI. Check for mistakes.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case it is use supplied values. if they wish to not use a directory separator at the end of the localRoot or remoteRoot then that's their decision. The path mappings is designed to replace the root substring with the specified equivalent.

continue;
}

if (localPath.StartsWith(mapping.LocalRoot, StringComparison.OrdinalIgnoreCase))
Copy link
Preview

Copilot AI Jul 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same path comparison issue as with TryGetMappedLocalPath. Using StartsWith without proper path boundary checking could lead to incorrect path mappings.

Suggested change
if (localPath.StartsWith(mapping.LocalRoot, StringComparison.OrdinalIgnoreCase))
if (localPath.StartsWith(mapping.LocalRoot, StringComparison.OrdinalIgnoreCase) &&
(localPath.Length == mapping.LocalRoot.Length ||
localPath[mapping.LocalRoot.Length] == System.IO.Path.DirectorySeparatorChar ||
localPath[mapping.LocalRoot.Length] == System.IO.Path.AltDirectorySeparatorChar))

Copilot uses AI. Check for mistakes.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jborean93
Copy link
Contributor Author

An example of how the pathMappings can be used for launching when the interactive terminal has entered a remote runspace. The editor sees the file under /home/jborean/dev/vscode-powershell/examples/test.ps1 but the pathMappings will map it to C:\temp\test.ps1 where that same script is located on the remote host.

{
  "name": "PowerShell Launch Script",
  "type": "PowerShell",
  "request": "launch",
  "script": "${workspaceFolder}/test.ps1",
  "cwd": "${cwd}",
  "pathMappings": [
    {
      "localRoot": "${workspaceFolder}/",
      "remoteRoot": "C:\\temp\\"
    }
  ]
},
image

It looks like I need to update the logic for the client breakpoint to contain the original workspace path and not the mapped remote file so I will fix that.

@jborean93 jborean93 closed this Jul 31, 2025
@jborean93 jborean93 reopened this Jul 31, 2025
@jborean93 jborean93 force-pushed the path-mapping branch 2 times, most recently from 0837fa1 to a182fe6 Compare August 5, 2025 19:48
Adds the `pathMappings` option to the debugger that can be used to map a
local to remote path and vice versa. This is useful if the local
environment has a checkout of the files being run on a remote target but
at a different path. The mappings are used to translate the paths that
will the breakpoint will be set to in the target PowerShell instance. It
is also used to update the stack trace paths received from the remote.

For a launch scenario, the path mappings are also used when launching a
script if the integrated terminal has entered a remote runspace.
@jborean93 jborean93 requested a review from a team as a code owner August 18, 2025 22:11

if (remotePath.StartsWith(mapping.RemoteRoot, StringComparison.OrdinalIgnoreCase))
{
localPath = mapping.LocalRoot + remotePath.Substring(mapping.RemoteRoot.Length);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does seem to me like the mapping would also be a directory (which may or may not be supplied with a trailing path separator); is there a good reason not to use path.combine?

Copy link
Contributor Author

@jborean93 jborean93 Aug 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the end user can supply any value they want and the matching is just a simple string substitution. For example I could have

{
    "pathMappings": [
        // Maps the whole directory from one to the other, any files/dirs
        // inside this directory will be mapped
        {
            "localRoot": "/path/src-checkout/",
            "remoteRoot": "C:\\remote\\path\src-checkout\\"
        },
        // Map an individual file, useful if you don't want to map
        // the whole directories contents and just a single file
        {
            "localRoot": "/path/some-script.ps1",
            "remoteRoot": "C:\\remote\\some-script.ps1"
        }
    ]
}

The mapping could either be part of the path or the whole path. Whether a user wants to map partially, the full path, or even some common prefix of a dir would be up to them to decide and not PSES.

catch
{
_debugService.UnsetPathMappings();
throw;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like there's a better pattern to apply here, but I'm not sure what. @SeeminglyScience for a suggestion (is there a way this can be done with a using? Is that too complicated?)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jborean93 should this be a finally instead of a catch? or are the path mappings unset somewhere else when there's no error? I guess that would have to be the case right? Handle returns before debugging is actually complete right?

(if the answer to the above is "no it needs to be a catch", then @andyleejordan: nah using wouldn't work here unfortunately as it's only unset when an exception occurs)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It can't be finally otherwise it'll unset the path mappings during the debug session. The finally would run when the AttachResponse is returned but we need it to stay there until the terminate/disconnect request.

return await HandleImpl(request, cancellationToken).ConfigureAwait(false);
}
catch
{
_debugService.IsDebuggingRemoteRunspace = false;
_debugService.UnsetPathMappings();
throw;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohh I see where that pattern came from now.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea it's done in the catch block to undo any setup work for the session in case of a fatal failure. The normal cleanup will happen in the terminal/disconnect handler which occurs when the debug session ends.

@@ -486,6 +522,7 @@ private async Task OnExecutionCompletedAsync(Task executeTask)
_debugEventHandlerService.UnregisterEventHandlers();

_debugService.IsDebuggingRemoteRunspace = false;
_debugService.UnsetPathMappings();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is probably not actually something to be solved in this PR, it seems like DebugService needs some sort of finalizer to handle "hey we're wrapping up now." Surprised it's not just disposed and recreated but I'd have to dig in to understand that more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea agreed, there are already a few comments peppered around the place saying there needs to be a better cleanup/stop mechanism for this.

IReadOnlyList<PSModuleInfo> dscModule =
await executionService.ExecutePSCommandAsync<PSModuleInfo>(
IReadOnlyList<string> dscModule =
await executionService.ExecutePSCommandAsync<string>(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok so these are now strings since we added the parameter to get the names instead of the modules directly. Why, what are we changing here? FWIW this is really old legacy code.

Copy link
Contributor Author

@jborean93 jborean93 Aug 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For an attach scenario across the process boundary the PSModuleInfo returned from the invoked pipeline will fail because it is serialized. Instead of returning the PSModuleInfo the code now just returns a simple string which is deserialized properly. The logic after wasn't even using PSModuleInfo just the number of objects returned.

nextStoppedTcs = new();

currentStoppedTcs.SetResult(e);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like this must fix something that's been broken/buggy with the tests. Can you elaborate?

Copy link
Contributor Author

@jborean93 jborean93 Aug 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was a race condition I (think I) encountered during testing. Consider the following code from one of the tests

...
StoppedEvent stoppedEvent = await nextStoppedTask;
nextStoppedTask = nextStopped;
...

// Later in the test
stoppedEvent = await nextStoppedTask;

When the current code did

nextStoppedTcs.SetResult(e);
nextStoppedTcs = new();

The await on the test side could have set nextStoppedTask from the nextStopped field before the OnStopped delegate created the new value. This meant the next time the test awaited that task it would get the old StoppedEvent from the original await. What this change does is to set the field first with a fresh TCS then complete the task so that when the tests return from the await the next nextStoppedTask = nextStopped will always be for a subsequent stop event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Path Mapping on Attach request
3 participants